package com.tarena.lbs.basic.web.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.repoistory.AdminRepository;
import com.tarena.lbs.basic.web.service.AdminService;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    //仓储层 仓储层和持久层 对应的是表格 一个表格
    @Autowired
    private AdminRepository adminRepository;

    @Override
    public AdminBO adminDetail() throws BusinessException {
        //1. 拿到登录用户id service一定是filter执行的线程下游
        Integer userId=getLoginUserId();
        //2. 调用仓储层 查询数据 select * from lbs_admin where id=#{id}
        log.debug("P1-查询持久层:{}",userId);
        AdminBO adminBO=adminRepository.getAdminById(userId);
        //3. 返回数据
        return adminBO;
    }

    @Override
    public AdminBO adminDetail(Integer adminId) throws BusinessException {
        //2. 调用仓储层 查询数据 select * from lbs_admin where id=#{id}
        AdminBO adminBO=adminRepository.getAdminById(adminId);
        //3. 返回数据
        return adminBO;
    }

    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public BasePageList<AdminBO> adminList(AdminQuery query) {
        log.debug("S2-查询参数:{}",query);
        return adminRepository.adminList(query);
    }

    @Override
    public void adminSave(AdminBO adminBO) throws BusinessException {
        log.info("当前新增商家账号入参：{}",adminBO);
        long total=adminRepository.countAdminByPhone(adminBO.getAccountPhone());
        if (total>0){
            throw new BusinessException("104","手机号已存在");
        }
        adminRepository.save(adminBO);
    }

    private Integer getLoginUserId() throws BusinessException {
        //1. 使用threadlocal获取 现成中存储的user数据
        UserPrinciple loginuser = LbsSecurityContenxt.getLoginToken();
        //2. 验证非空 才获取id返回
        if (ObjectUtils.isEmpty(loginuser)){
            throw new BusinessException("102","登录用户数据不存在");
        }
        return loginuser.getId();
    }
}
